package com.liuning.graduationdemo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuning.graduationdemo.common.Constants;
import com.liuning.graduationdemo.dto.UserDTO;
import com.liuning.graduationdemo.entity.Menu;
import com.liuning.graduationdemo.entity.User;
import com.liuning.graduationdemo.exception.ServiceException;
import com.liuning.graduationdemo.mapper.RoleMapper;
import com.liuning.graduationdemo.mapper.RoleMenuMapper;
import com.liuning.graduationdemo.mapper.UserMapper;
import com.liuning.graduationdemo.service.IMenuService;
import com.liuning.graduationdemo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuning.graduationdemo.utils.TokenUtils;
import org.apache.ibatis.annotations.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pumpkin
 * @since 2022-04-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;

    @Resource
    private UserMapper userMapper;

    //打印日志
    private final Log LOG = Log.get();

    @Override
    public UserDTO login(UserDTO userDTO) {
        User user = getUserInfo(userDTO);
        if (user != null) {
            BeanUtil.copyProperties(user,userDTO,true);
            //设置token
            String token = TokenUtils.generateToken(user.getId().toString(), user.getPassword());
            userDTO.setToken(token);
            //根据role（ROLE_USER）获取菜单数据
            String role = user.getRole();

            //获取当前角色的菜单列表
            userDTO.setMenus(getRoleMenus(role));

            return userDTO;
        }else {
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }

    @Override
    public User register(UserDTO userDTO) {
        User user = getUserInfo(userDTO);
        if (user == null) {
            user = new User();
            user.setRole("ROLE_PATIENT");
            BeanUtil.copyProperties(userDTO,user,true);
            save(user);
        }else {
            throw new ServiceException(Constants.CODE_600,"用户名已存在");
        }
        return user;
    }

    @Override
    public Page<User> findPage(Page<User> page, String username, String nickname, String address,String roleType) {
        return userMapper.findPage(page,username,nickname,address,roleType);
    }

    @Override
    public Page<User> findDoctorPage(Page<User> page, String nickname, Integer deptId,String roleType) {
        return userMapper.findDoctorPage(page,nickname,deptId,roleType);
    }

    @Override
    public Page<User> findPatientPage(Page<User> page, String nickname, String roleType) {
        return userMapper.findPatientPage(page,nickname,roleType);
    }

    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userDTO.getUsername());
        queryWrapper.eq("password",userDTO.getPassword());
        User user = null;
        try {
            user = getOne(queryWrapper);
        }catch (Exception e){
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return user;
    }

    /**
     * 获取当前角色的菜单列表
     * @param roleFlags
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlags) {

        Integer roleId = roleMapper.selectByFlag(roleFlags);
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);

        //筛选完成后的菜单
        List<Menu> roleMenus = new ArrayList<>();
        //查出系统所有的菜单
        List<Menu> menus = menuService.findMenus("");
        //筛选当前用户角色的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            //移除children里面不在menuIds集合中的元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        roleMenus.forEach(System.out::println);
        return roleMenus;
    }
}
